import { ReactNode } from 'react';
import _ from 'lodash';
import { App } from '../pages/home/App';
import { PageNotFound } from '../components/PageNotFound';
import homeRoute from '../pages/home/route';

export interface RouteType {
  path: string;
  name?: string;
  component?: ReactNode;
  childRoutes?: RouteType[];
  isIndex?: boolean;
  exact?: boolean;
  autoIndexRoute?: boolean;
} 

const childRoutes = [
  homeRoute
]

// Handle isIndex property of route config:
// Dupicate it and put it as the first route rule.
export const routes: RouteType[] = [{
  path: '/',
  component: App,
  childRoutes: [
    ...childRoutes,
    { path: '*', name: 'Page not found', component: PageNotFound},
  ].filter((r: RouteType) => r.component || (r.childRoutes && r.childRoutes.length > 0))
}]

const handleIndexRoute = (route: RouteType) => {
  if (!route.childRoutes || !route.childRoutes.length) {
    return;
  }

  const indexRoute: RouteType = _.find(route.childRoutes, ((child: RouteType) => child.isIndex)) as RouteType;
  if (indexRoute) {
    const first = { ...indexRoute };
    first.path = '';
    first.exact = true;
    first.autoIndexRoute = true; // mark it so that the simple nav won't show it.
    route.childRoutes.unshift(first);
  }
  route.childRoutes.forEach(handleIndexRoute);
}

routes.forEach(handleIndexRoute);
